package cpa.prowon.image;

import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Canvas;

import cpa.prowon.gui.image.*;

/**
 * Manages creating thumbnails by using own threads for thumbnail creation
 * @author Chris
 */
public class ThumbnailManager {

	// Properties
	private static ThumbnailManager _instance;
	private ImageRegistry image_registry;
	private Thread currentThread;
	
	/**
	 * Constructor. Currently private because it's used as singleton
	 * @author Chris
	 */
	private ThumbnailManager() {
	}
	
	/**
	 * Return the one and only instance
	 * @return The one and only ThumbnailManager instance 
	 * @author Chris
	 */
	public static ThumbnailManager getInstance() {
		if (_instance == null) {
			_instance = new ThumbnailManager();	
		}
		return _instance;
	}
	
	/**
	 * Return the image registry, if it was not yet created it gets created
	 * @return The ImageRegistry object
	 * @author Chris
	 */
	protected ImageRegistry getImageRegistry() {
		
		// If the image registry was not created yet, create it
		if (image_registry == null) {
			image_registry = new ImageRegistry();
		}
		
		// Return the image registry
		return image_registry;
		
	}
	
	/**
	 * Get a thumbnail for the given image container
	 * @param Display The display used by the main window
	 * @param String The path name of the image
	 * @author Chris
	 */
	public Image getThumbnail(ImageContainer input_image) {
		
		// Try to get the thumbnail from the image registry
		Image theImage = getImageRegistry().get(input_image.getPathName());
		
		// Return the image
		return theImage;
		
	}

	/**
	 * Cache the given image in the image registry
	 * @param ImageContainer The image container describing the image
	 * @param Image The actual image
	 * @author Chris
	 */
	public void cacheThumbnail(ImageContainer input_image, Image image) {
		
		// Try to get the thumbnail from the image registry
		getImageRegistry().put(input_image.getPathName(), image);
		
	}

	/**
	 * Create a thumbnail in an own thread
	 * @param ImageContainer The image container the holds the reference to the image
	 * @param Canvas The canvas where the thumbnail shall be shown
	 * @author Chris
	 */
	public void createThumbnail(ImageContainer ic, Canvas canvas) {
		
		// Check whether or not there is already a thread running
		boolean createNewThread = false;
		if (currentThread != null) {
			if (!currentThread.getName().equals(ic.getPathName())) {
				if (currentThread.isAlive()) {
					currentThread.interrupt();
				}
				createNewThread = true;
			}
		} else {
			createNewThread = true;
		}
		
		// Create a new thread if necessary
		if (createNewThread == true) {
			currentThread = new ThumbnailDisplayer(ic, canvas);
			currentThread.setName(ic.getPathName());
			currentThread.start();
		}

	}
	
}
